package com.atguigu.tingshu.album.api;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.common.result.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Tag(name = "上传管理接口")
@RestController
@RequestMapping("api/album")
public class FileUploadApiController {

    @Autowired
    private MinioConstantProperties minioConstantProperties;
//    文件上传
    @Operation(summary = "文件上传")
    @PostMapping("fileUpload")
    public Result uploadFile(@Parameter(name = "file",description = "上传的文件名") MultipartFile file) {
        MinioClient minioClient = MinioClient.builder().endpoint(minioConstantProperties.getEndpointUrl()).credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey()).build();
        String url = "";
        try {
            boolean flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            if (!flag){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            }
            String houzhui = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = UUID.randomUUID().toString().replaceAll("-","")+houzhui;
            minioClient.putObject(PutObjectArgs.builder().bucket(minioConstantProperties.getBucketName()).object(fileName).contentType(file.getContentType()).stream(file.getInputStream(),file.getSize(),-1).build());
            url = minioConstantProperties.getEndpointUrl()+"/"+minioConstantProperties.getBucketName()+"/"+fileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.ok(url);
    }


}
